package com.gugu.procedure.service;

import com.alibaba.druid.support.json.JSONUtils;
import com.gugu.procedure.bean.*;
import com.gugu.procedure.common.Constant;
import com.gugu.procedure.common.MessageResult;
import com.gugu.procedure.dao.*;
import com.gugu.procedure.exceptions.BusinessException;
import com.gugu.procedure.param.InsideOrderAddParam;
import com.gugu.procedure.param.InsideOrderCheckParam;
import com.gugu.procedure.util.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import javax.persistence.criteria.Predicate;
import java.io.File;
import java.util.*;
import java.util.stream.Collectors;

@Service
public class InsideOrderService {

    @Value("${system.file_path}")
    public String pathPrefix;
    @Autowired
    private InsideOrderDao insideOrderDao;
    @Autowired
    private OrderItemDao orderItemDao;
    @Autowired
    private ParameterDao parameterDao;
    @Autowired
    private ProductionDao productionDao;
    @Autowired
    private CustInfoService custInfoService;
    @Autowired
    private CheckRecordDao checkRecordDao;
    @Autowired
    private OrderProductionRecordDao orderProductionRecordDao;
    @Autowired
    private ProductionRecordDao productionRecordDao;
    @Autowired
    private ReplenishmentDao replenishmentDao;
    @Autowired
    private WorkDoneDao workDoneDao;
    @Autowired
    private ProductionService productionService;

    public List <InsideOrder> findAllByStatus(String status) {
        return insideOrderDao.findAllByStatus(status);
    }

    public Page <InsideOrder> findByStatus(String status, String orderNo, String type, int pageNo, int pageSize) {
        Specification <InsideOrder> spec = (Specification <InsideOrder>) (root, query, cb) -> {
            List <Predicate> list = new ArrayList <>();
            if (StringUtils.hasText(status)) {
                list.add(cb.equal(root.get("status").as(String.class), status));
            }
            if (StringUtils.hasText(orderNo)) {
                list.add(cb.equal(root.get("orderNo").as(String.class), orderNo));
            }
            if (StringUtils.hasText(type)) {
                list.add(cb.equal(root.get("type").as(String.class), type));
            }
            Predicate[] pre = new Predicate[list.size()];
            query.where(list.toArray(pre));
            return query.getRestriction();
        };
        PageRequest pr = PageRequest.of(pageNo - 1, pageSize, Sort.Direction.DESC, "createTime");
        Page <InsideOrder> recordsPage = insideOrderDao.findAll(spec, pr);
        return recordsPage;
    }

    @Transactional
    public MessageResult add(InsideOrderAddParam insideOrderAddParam) {
        String type = "U";
        if (insideOrderAddParam.getUrl().startsWith("N")) {
            type = "N";
        }
        File file = new File(pathPrefix + insideOrderAddParam.getUrl());
        Map <String, Object> map = OrderUtil.resolvingInsideOrder(file, insideOrderAddParam.getType());
        InsideOrder insideOrder = (InsideOrder) map.get("insideOrder");
        insideOrder.setCreateTime(DateUtil.getFormatedDate());
        insideOrder.setBusinessDate(insideOrder.getOrderDate());
        List <OrderItem> list = (List <OrderItem>) map.get("list");
        InsideOrder temp = insideOrderDao.findTopByOrderNo(insideOrder.getOrderNo());
        if (Objects.nonNull(temp)) {
            return MessageResult.error("该订单已存在");
        }
        if (list == null || list.size() == 0) {
            return MessageResult.error("订单项为空，请重新检查文件");
        }
        // 客户特殊要求处理
        String cust_no = list.get(0).getCustNo();
        CustInfo custInfo = custInfoService.findTopByCustNo(cust_no);
        if (custInfo != null) {
            insideOrder.setSpecialRequirements(custInfo.getRequirements());
        }
        insideOrder.setType(type);
        insideOrder.setUrl(insideOrderAddParam.getUrl());
        // 新品订单模具编号处理  如果excel中已经标明了模具编号 则不需要系统自动赋予
        if (StringUtil.isEmpty(list.get(0).getNumberStart())) {
            String yyMM = DateUtil.getDate().substring(2, 6);
            if (StringUtil.equals(type, "N")) {
                String nextNewNumber = null;
                for (int index = 0; index < list.size(); index++) {
                    OrderItem orderItem = list.get(index);
                    String custNo = orderItem.getCustNo();
                    if (Objects.isNull(nextNewNumber)) {
                        if (StringUtil.isEmpty(custNo)) {
                            return MessageResult.error("客户编码为空");
                        }
                        nextNewNumber = custInfoService.nextNewNumber(custNo);
                    }
                    Integer num = Integer.parseInt(orderItem.getAmount());
                    orderItem.setNumberStart(nextNewNumber);
                    String numberEnd = orderItem.getNumberStart();
                    for (int i = 1; i < num; i++) {
                        numberEnd = NumberUtil.nextNumber(numberEnd);
                    }
                    orderItem.setNumberEnd(numberEnd);
                    if (index < list.size() - 1) {
                        nextNewNumber = NumberUtil.nextNumber(numberEnd);
                    } else {
                        custInfoService.updateNumber(custNo, NumberUtil.nextNumber(numberEnd));
                    }
                }
            } else {
                // 修理订单不能用新品订单的模具编号规格
                String nextNewNumber = "1";
                for (int index = 0; index < list.size(); index++) {
                    OrderItem orderItem = list.get(index);
                    Integer num = Integer.parseInt(orderItem.getAmount());
                    orderItem.setNumberStart(nextNewNumber);
                    String numberEnd = orderItem.getNumberStart();
                    for (int i = 1; i < num; i++) {
                        numberEnd = (Integer.parseInt(numberEnd) + 1) + "";
                    }
                    orderItem.setNumberEnd(numberEnd);
                    nextNewNumber = (Integer.parseInt(numberEnd) + 1) + "";
                }
            }


        }
        // 模具编号不能为空
        insideOrderDao.save(insideOrder);
        orderItemDao.saveAll(list);
        return MessageResult.success();
    }


    public MessageResult page(String role, String orderNo, String custOrderNo, String custCompany, String
            customer, String param, String startTime, String endTime, String status, int pageNo, int pageSize) {
        Specification <InsideOrder> spec = (Specification <InsideOrder>) (root, query, cb) -> {
            List <Predicate> list = new ArrayList <>();
            if (StringUtils.hasText(orderNo)) {
                list.add(cb.equal(root.get("orderNo").as(String.class), orderNo));
            }
            if (StringUtils.hasText(custOrderNo)) {
                list.add(cb.equal(root.get("custOrderNo").as(String.class), custOrderNo));
            }
            if (StringUtils.hasText(custCompany)) {
                list.add(cb.like(root.get("custCompany").as(String.class), "%" + custCompany + "%"));
            }
            if (StringUtils.hasText(customer)) {
                list.add(cb.like(root.get("customer").as(String.class), "%" + customer + "%"));
            }
            if (StringUtils.hasText(status)) {
                list.add(cb.equal(root.get("status").as(String.class), status));
            }
            if (StringUtils.hasText(startTime) && StringUtils.hasText(endTime)) {
                list.add(cb.between(root.get("createTime").as(String.class), startTime, endTime));
            }
            if (StringUtils.hasText(param)) {
                list.add(cb.notLike(root.get("checkRecords").as(String.class), "%" + param + "%"));
            }
            Predicate[] pre = new Predicate[list.size()];
            query.where(list.toArray(pre));
            return query.getRestriction();
        };
        PageRequest pr = PageRequest.of(pageNo - 1, pageSize, Sort.Direction.DESC, "createTime");
        Page <InsideOrder> recordsPage = insideOrderDao.findAll(spec, pr);
        // 订单状态转义
        /**
         * 审批流程
         * 1技术
         * 2计划
         * 3品管
         * 4生产
         */
        //  如果是四大角色  则需要判断其是否给其他角色审核过  如果审核过 则显示审核中 如果没有 则显示待审核
        // 处理是否显示审核按钮
        if (Constant.CHECK_ROLES.contains(role)) {
            for (InsideOrder insideOrder : recordsPage.getContent()) {
                String checkRecords = insideOrder.getCheckRecords() == null ? "" : insideOrder.getCheckRecords();
                // 处理是否显示审核按钮
                if (Constant.MANAGER_TECHNOLOGY.equals(role)) {
                    if (checkRecords.contains(role)) {
                        insideOrder.setCheckFlag("0");
                    } else {
                        insideOrder.setCheckFlag("1");
                    }
                } else if (Constant.MANAGER_PLAIN.equals(role)) {
                    if (checkRecords.contains(Constant.MANAGER_TECHNOLOGY) && !checkRecords.contains(Constant.MANAGER_PLAIN)) {
                        insideOrder.setCheckFlag("1");
                    } else {
                        insideOrder.setCheckFlag("0");
                    }
                } else if (Constant.MANAGER_QC.equals(role)) {
                    if (checkRecords.contains(Constant.MANAGER_TECHNOLOGY) && checkRecords.contains(Constant.MANAGER_PLAIN) && !checkRecords.contains(Constant.MANAGER_QC)) {
                        insideOrder.setCheckFlag("1");
                    } else {
                        insideOrder.setCheckFlag("0");
                    }
                } else if (Constant.MANAGER_PRODUCTION.equals(role)) {
                    if (checkRecords.contains(Constant.MANAGER_TECHNOLOGY) && checkRecords.contains(Constant.MANAGER_PLAIN)
                            && checkRecords.contains(Constant.MANAGER_QC) && !checkRecords.contains(Constant.MANAGER_PRODUCTION)) {
                        insideOrder.setCheckFlag("1");
                    } else {
                        insideOrder.setCheckFlag("0");
                    }
                }
//                if (Constant.ORDER_STATUS_1.equals(insideOrder.getStatus())) {
//                    if (insideOrder.getCheckRecords() == null || !insideOrder.getCheckRecords().contains(role)) {
//                        insideOrder.setCheckStatus(Constant.ORDER_STATUS_0);
//                    } else {
//                        insideOrder.setCheckStatus("");
//                    }
//                }
            }
        }

        for (InsideOrder insideOrder : recordsPage.getContent()) {
            //  处理显示订单状态
            String checkRecords = insideOrder.getCheckRecords() == null ? "" : insideOrder.getCheckRecords();
            String orderStatus = insideOrder.getStatus();
            if (Constant.ORDER_STATUS_0.equals(orderStatus)) {
                insideOrder.setStatusStr("待技术审核");
            } else if (Constant.ORDER_STATUS_2.equals(orderStatus)) {
                insideOrder.setStatusStr("审核拒绝");
            } else if (Constant.ORDER_STATUS_3.equals(orderStatus)) {
                insideOrder.setStatusStr("流转中");
            } else if (Constant.ORDER_STATUS_4.equals(orderStatus)) {
                insideOrder.setStatusStr("已完成");
            } else if (Constant.ORDER_STATUS_1.equals(orderStatus)) {
                if (checkRecords.contains(Constant.MANAGER_TECHNOLOGY) && !checkRecords.contains(Constant.MANAGER_PLAIN)) {
                    insideOrder.setStatusStr("待计划审批");
                } else if (checkRecords.contains(Constant.MANAGER_TECHNOLOGY) && checkRecords.contains(Constant.MANAGER_PLAIN) && !checkRecords.contains(Constant.MANAGER_QC)) {
                    insideOrder.setStatusStr("待品管审批");
                } else if (checkRecords.contains(Constant.MANAGER_TECHNOLOGY) && checkRecords.contains(Constant.MANAGER_PLAIN)
                        && checkRecords.contains(Constant.MANAGER_QC) && !checkRecords.contains(Constant.MANAGER_PRODUCTION)) {
                    insideOrder.setStatusStr("待生产课审批");
                }
            }
        }
        MessageResult mr = MessageResult.success();
        mr.setTotal(recordsPage.getTotalElements());
        mr.setTotalElement(recordsPage.getContent());
        return mr;
    }


    /**
     * 订单详情
     *
     * @param orderNo
     * @param item    这个可能是规格 也可能是模具编号  根据订单类型判断
     *                是新订单就是模具编号 修理订单就是规格号
     * @return
     */
    public MessageResult insideOrderDetail(String orderNo, String item) {
        Map <String, Object> map = new HashMap <>();
        InsideOrder insideOrder = insideOrderDao.findTopByOrderNo(orderNo);
        if (Objects.isNull(insideOrder)) {
            return MessageResult.error("该订单不存在");
        }
        List <OrderItem> list = null;
        if (StringUtil.isEmpty(item)) {
            list = orderItemDao.findByOrderNo(orderNo);
        } else {
            if (Constant.ORDER_TYPE_U.equals(insideOrder.getType())) {
                OrderItem orderItem = orderItemDao.findTopByOrderNoAndSpecs(orderNo, item);
                list.add(orderItem);
            } else {
                list = orderItemDao.findByOrderNoAndNumberStartIsLessThanEqualAndNumberEndIsGreaterThanEqual(orderNo, item, item);
            }
        }
        List <Parameter> parameters = parameterDao.findByOrderNoOrderBySequeDesc(insideOrder.getOrderNo());
        map.put("insideOrder", insideOrder);
        list = list.stream().sorted(Comparator.comparing(OrderItem::getId)).collect(Collectors.toList());
        parameters = parameters.stream().sorted(Comparator.comparing(Parameter::getId)).collect(Collectors.toList());
        map.put("orderItem", list);
        map.put("parameters", parameters);
        return MessageResult.getSuccessInstance(map);
    }

    @Transactional
    public void saveParameterList(List <Parameter> list) {
        for (Parameter parameter : list) {
            Parameter bean = saveParameter(parameter);
            dealProcedure(bean);
        }
    }


    /**
     * 根据订单参数生产工序
     *
     * @param parameter
     */
    private void dealProcedure(Parameter parameter) {
        Production production = new Production();
        production.setOrderNo(parameter.getOrderNo());
        production.setSeque(parameter.getSeque());
        production.setSpecs(parameter.getSpecs());
        List <String> list = new ArrayList <>();
        // 流程：激光-整形-扩大-成形-一设-斜线一研-设定-二研-品管
        // 激光 - 整形 - 扩大 - 成形 - 一设 - 过粉 - 斜线-一研 - 设定 - 二研 - 品管（镜检 - 挪检 - 车制 - 打码 - 包装）
        // 流程：激光-整形-扩大-成形-一设-过粉-一研-设定-二研-品管（镜检-挪检-车制-打码-包装）
        // 流程：激光一整形-扩大-成形-过粉-斜线-一研-设定-油粉-品管（镜检-挪检-车制-打码-包装）
        // 激光--不加入工序流程
        if (StringUtil.isNotEmpty(parameter.getLaserParamUp1()) || StringUtil.isNotEmpty(parameter.getLaserParamUp2()) || StringUtil.isNotEmpty(parameter.getLaserParamDown1())
                || StringUtil.isNotEmpty(parameter.getLaserParamDown2()) || StringUtil.isNotEmpty(parameter.getLaserParamAngle())) {
            //激光--不加入工序流程
            // list.add(Constant.PROCEDURE_LASER);
        }
        // 整形
        if (StringUtil.isNotEmpty(parameter.getPlastic())) {
            list.add(Constant.PROCEDURE_PLASTIC);
        }
        // 扩大
        if (StringUtil.isNotEmpty(parameter.getKdAllowanceUp()) || StringUtil.isNotEmpty(parameter.getKdAllowanceDown())) {
            list.add(Constant.PROCEDURE_EXPANSION);
        }
        //  成形
        if (StringUtil.isNotEmpty(parameter.getCxAllowanceUp()) || StringUtil.isNotEmpty(parameter.getCxAllowanceDown())) {
            list.add(Constant.PROCEDURE_FORMING);
        }

        //  一设
        if (StringUtil.isNotEmpty(parameter.getYsUp()) || StringUtil.isNotEmpty(parameter.getYsDown())) {
            list.add(Constant.PROCEDURE_SET1);
        }
        // 过粉1
        if (StringUtil.isNotEmpty(parameter.getGf1Up())
                || StringUtil.isNotEmpty(parameter.getGf1Down())) {
            list.add(Constant.PROCEDURE_GF1);
        }
        // 过粉2
        if (StringUtil.isNotEmpty(parameter.getGf2Up())
                || StringUtil.isNotEmpty(parameter.getGf2Down())) {
            list.add(Constant.PROCEDURE_GF2);
        }

        //  斜线
        if (StringUtil.isNotEmpty(parameter.getXxAllowanceUp()) || StringUtil.isNotEmpty(parameter.getXxAllowanceDown())) {
            list.add(Constant.PROCEDURE_SLASH);
        }
        //  一研
        if (StringUtil.isNotEmpty(parameter.getResearch1())) {
            list.add(Constant.PROCEDURE_RESEARCH1);
        }
        // 设定
        if (StringUtil.isNotEmpty(parameter.getDjAllowanceUp1()) || StringUtil.isNotEmpty(parameter.getDjAllowanceUp2())
                || StringUtil.isNotEmpty(parameter.getDjAllowanceDown1()) || StringUtil.isNotEmpty(parameter.getDjAllowanceDown2())) {
            list.add(Constant.PROCEDURE_SETING);
        }
        // 二研
        if (StringUtil.isNotEmpty(parameter.getResearch2())) {
            list.add(Constant.PROCEDURE_RESEARCH2);
        }
        // 油粉

        //品管（镜检-挪检-车制-打码-包装）
        if (StringUtil.isNotEmpty(parameter.getQcjj())) {
            list.add(Constant.PROCEDURE_QC_JJ);
        }

        if (StringUtil.isNotEmpty(parameter.getQclj())) {
            list.add(Constant.PROCEDURE_QC_LJ);
        }

        if (StringUtil.isNotEmpty(parameter.getQccz())) {
            list.add(Constant.PROCEDURE_QC_CZ);
        }
        if (StringUtil.isNotEmpty(parameter.getQcdm())) {
            list.add(Constant.PROCEDURE_QC_DM);
        }
        if (StringUtil.isNotEmpty(parameter.getQcbz())) {
            list.add(Constant.PROCEDURE_QC_BZ);
        }


        //  品管
        //  list.add(Constant.PROCEDURE_QC);

        production.setParameterId(parameter.getId());
        production.setProcedures(JSONUtils.toJSONString(list));
        productionSave(production);

    }

    @Transactional
    public void productionSave(Production production) {
        Production bean = productionDao.findTopByOrderNoAndSpecs(production.getOrderNo(), production.getSpecs());
        if (Objects.nonNull(bean)) {
            production.setId(bean.getId());
        }
        productionDao.save(production);
    }


    @Transactional
    public Parameter saveParameter(Parameter parameter) {
        Parameter bean = parameterDao.findTopByOrderNoAndSpecs(parameter.getOrderNo(), parameter.getSpecs());
        if (Objects.nonNull(bean)) {
            parameter.setId(bean.getId());
        }
        parameter = parameterDao.saveAndFlush(parameter);
        return parameter;
    }

    public void updateOrderItem(OrderItem orderItem) {
        orderItemDao.save(orderItem);
    }

    public void updateOrderItemList(List <OrderItem> list) {
        orderItemDao.saveAll(list);
    }

    public OrderItem findByOrderNoAndSeque(String orderNo, String seque) {
        return orderItemDao.findTopByOrderNoAndSeque(orderNo, seque);
    }


    public OrderItem findTopByOrderNoAndSpecs(String orderNo, String specs) {
        return orderItemDao.findTopByOrderNoAndSpecs(orderNo, specs);
    }

    // 根据订单和模具编号查询订单报送页面所需信息
    public OrderItem queryByOrderNoAndNumber(String orderNo, String number) {
        OrderItem orderItem = orderItemDao.queryByOrderNoAndNumberForUpdate(orderNo, number);
        return orderItem;
        //查询订单信息
    }


    public List <Map <String, String>> queryParams(String orderNo, String specs, String production) {
        List <Map <String, String>> mapList = new ArrayList <>();
        Parameter parameter = parameterDao.findTopByOrderNoAndSpecs(orderNo, specs);
        if (parameter != null) {
            //  一设 设定
            if (production.contains(Constant.PROCEDURE_SET1) || production.contains(Constant.PROCEDURE_SETING)) {
                Map <String, String> map1 = new HashMap <>();
                map1.put("label", "定经余量上限1");
                map1.put("value", parameter.getDjAllowanceUp1());

                Map <String, String> map2 = new HashMap <>();
                map2.put("label", "定经余量上限2");
                map2.put("value", parameter.getDjAllowanceUp2());


                Map <String, String> map3 = new HashMap <>();
                map3.put("label", "定经余量下限1");
                map3.put("value", parameter.getDjAllowanceDown1());

                Map <String, String> map4 = new HashMap <>();
                map4.put("label", "定经余量下限2");
                map4.put("value", parameter.getDjAllowanceDown2());

                mapList.add(map1);
                mapList.add(map2);
                mapList.add(map3);
                mapList.add(map4);
            }
            //斜线
            else if (production.contains(Constant.PROCEDURE_SLASH)) {

                Map <String, String> map1 = new HashMap <>();
                map1.put("label", "斜线余量上限");
                map1.put("value", parameter.getXxAllowanceUp());

                Map <String, String> map2 = new HashMap <>();
                map2.put("label", "斜线余量下限");
                map2.put("value", parameter.getXxAllowanceDown());

                mapList.add(map1);
                mapList.add(map2);
            }
            //成形
            else if (production.contains(Constant.PROCEDURE_FORMING)) {

                Map <String, String> map1 = new HashMap <>();
                map1.put("label", "成形余量上限");
                map1.put("value", parameter.getCxAllowanceUp());

                Map <String, String> map2 = new HashMap <>();
                map2.put("label", "成形余量下限");
                map2.put("value", parameter.getCxAllowanceDown());

                mapList.add(map1);
                mapList.add(map2);
            }

            //扩大
            else if (production.contains(Constant.PROCEDURE_EXPANSION)) {

                Map <String, String> map1 = new HashMap <>();
                map1.put("label", "扩大余量上限");
                map1.put("value", parameter.getKdAllowanceUp());

                Map <String, String> map2 = new HashMap <>();
                map2.put("label", "扩大余量下限");
                map2.put("value", parameter.getKdAllowanceDown());

                mapList.add(map1);
                mapList.add(map2);
            }

            //激光
            else if (production.contains(Constant.PROCEDURE_LASER)) {

                Map <String, String> map1 = new HashMap <>();
                map1.put("label", "激光参数上限1");
                map1.put("value", parameter.getLaserParamUp1());

                Map <String, String> map2 = new HashMap <>();
                map2.put("label", "激光参数上限2");
                map2.put("value", parameter.getLaserParamUp2());


                Map <String, String> map3 = new HashMap <>();
                map3.put("label", "激光参数下限1");
                map3.put("value", parameter.getLaserParamDown1());

                Map <String, String> map4 = new HashMap <>();
                map4.put("label", "激光参数下限2");
                map4.put("value", parameter.getLaserParamDown2());

                Map <String, String> map5 = new HashMap <>();
                map5.put("label", "激光参数角度");
                map5.put("value", parameter.getLaserParamAngle());

                mapList.add(map1);
                mapList.add(map2);
                mapList.add(map3);
                mapList.add(map4);
                mapList.add(map5);
            }

        }
        return mapList;
    }

    public OrderItem queryOrderItemByOrderNoAndNumber(String orderNo, String number) {
        return orderItemDao.queryByOrderNoAndNumberForUpdate(orderNo, number);
    }


    public InsideOrder queryInsideOrderByOrderNo(String orderNo) {
        return insideOrderDao.findTopByOrderNo(orderNo);
    }

    public void updateInsideOrder(InsideOrder insideOrder) {
        insideOrderDao.save(insideOrder);
    }

    //订单删除
    @Transactional
    public MessageResult remove(String orderNo) {
        //   删除参数表
        parameterDao.deleteAllByOrderNo(orderNo);
        //  删除工序表
        productionDao.deleteAllByOrderNo(orderNo);

        checkRecordDao.deleteAllByOrderNo(orderNo);

        insideOrderDao.deleteAllByOrderNo(orderNo);

        orderItemDao.deleteAllByOrderNo(orderNo);

        orderProductionRecordDao.deleteAllByOrderNo(orderNo);

        productionRecordDao.deleteAllByOrderNo(orderNo);

        replenishmentDao.deleteAllByOrderNo(orderNo);

        workDoneDao.deleteAllByOrderNo(orderNo);

        return MessageResult.success();
    }


    // 参数表校验

    /**
     * 规格和序号
     * 订单项有的     * @param orderNo
     *
     * @param list
     */
    private void checkParameter(String orderNo, List <Parameter> list) {
        List <OrderItem> orderItems = orderItemDao.findByOrderNo(orderNo);
        for (OrderItem orderItem : orderItems) {
            boolean flag = false;
            String seque = orderItem.getSeque();
            String specs = orderItem.getSpecs();
            for (Parameter parameter : list) {
                if (parameter.getSeque().equals(seque) && parameter.getSpecs().trim().equals(specs.trim())) {
                    flag = true;
                }
            }
            if (!flag) {
                throw new BusinessException("序号为" + seque + "的参数记录存在异常，请先核对后再导入");
            }
        }

    }

    /**
     * 参数重新导入  智慧更新工序表和参数表 不会修改流转状态
     *
     * @param account
     * @param insideOrderCheckParam
     * @return
     */
    @Transactional
    public MessageResult paramRetry(String account, InsideOrderCheckParam insideOrderCheckParam) {
        InsideOrder insideOrder = queryInsideOrderByOrderNo(insideOrderCheckParam.getOrderNo());
        if (StringUtil.isNotEmpty(insideOrderCheckParam.getParameterUrl())) {
            File file = new File(pathPrefix + insideOrderCheckParam.getParameterUrl());
            if (!file.exists()) {
                return MessageResult.error("参数文件不存在");
            }
            List <Parameter> list = OrderUtil.resolvingParameter(file, insideOrderCheckParam.getOrderNo(), account);
            //参数校验
            checkParameter(insideOrderCheckParam.getOrderNo(), list);
            // 保存之前 先清空  避免第二次导入参数表引发数据重复问题
            parameterDao.deleteAllByOrderNo(insideOrder.getOrderNo());
            //  删除工序表
            productionDao.deleteAllByOrderNo(insideOrder.getOrderNo());

            this.saveParameterList(list);

        }
        return MessageResult.success();
    }

    @Transactional
    public MessageResult checkOrder(String role, String account, String name, InsideOrderCheckParam
            insideOrderCheckParam) {
        InsideOrder insideOrder = queryInsideOrderByOrderNo(insideOrderCheckParam.getOrderNo());
        if (StringUtil.isNotEmpty(insideOrderCheckParam.getParameterUrl())) {
            File file = new File(pathPrefix + insideOrderCheckParam.getParameterUrl());
            if (!file.exists()) {
                return MessageResult.error("参数文件不存在");
            }
            List <Parameter> list = OrderUtil.resolvingParameter(file, insideOrderCheckParam.getOrderNo(), account);
            //参数校验
            checkParameter(insideOrderCheckParam.getOrderNo(), list);
            // 保存之前 先清空  避免第二次导入参数表引发数据重复问题
            parameterDao.deleteAllByOrderNo(insideOrder.getOrderNo());
            //  删除工序表
            productionDao.deleteAllByOrderNo(insideOrder.getOrderNo());
            this.saveParameterList(list);
        }
        if (insideOrderCheckParam.getStatus().equals(Constant.ORDER_STATUS_3)) {
            if (!insideOrder.getStatus().equals(Constant.ORDER_STATUS_2)) {
                insideOrder.setStatus(Constant.ORDER_STATUS_1);
            }
        } else if (insideOrderCheckParam.getStatus().equals(Constant.ORDER_STATUS_2)) {
            insideOrder.setStatus(Constant.ORDER_STATUS_2);
        }
        String checkRecords = insideOrder.getCheckRecords() == null ? "" : insideOrder.getCheckRecords();
        checkRecords = role + "," + checkRecords;
        insideOrder.setCheckRecords(checkRecords);
        String reason = insideOrder.getReason() == null ? "" : insideOrder.getReason();
        if (StringUtil.isNotEmpty(insideOrderCheckParam.getReason())) {
            reason = reason + "," + insideOrderCheckParam.getReason();
            insideOrder.setReason(reason);
        }
        // 如果 checkRecord 包含了四个角色 并且都是通过  则说明订单可以开始流转了

        if (insideOrderCheckParam.getStatus().equals(Constant.ORDER_STATUS_3)
                && checkRecords.contains(Constant.MANAGER_PRODUCTION) && checkRecords.contains(Constant.MANAGER_QC)
                && checkRecords.contains(Constant.MANAGER_PLAIN) && checkRecords.contains(Constant.MANAGER_TECHNOLOGY)) {
            insideOrder.setStatus(Constant.ORDER_STATUS_3);
            //默认将第一个工序的开始工艺给做了
            initFirstProduction(insideOrder.getOrderNo());
        }
        // 处理审核时间 和审核人
        if (Constant.MANAGER_PLAIN.equals(role)) {
            insideOrder.setPlan(name);
            insideOrder.setPlanDate(DateUtil.getFormatedDate());
        } else if (Constant.MANAGER_TECHNOLOGY.equals(role)) {
            insideOrder.setTechnology(name);
            insideOrder.setTechnologyDate(DateUtil.getFormatedDate());
        } else if (Constant.MANAGER_QC.equals(role)) {
            insideOrder.setQc(name);
            insideOrder.setQcDate(DateUtil.getFormatedDate());
        } else if (Constant.MANAGER_PRODUCTION.equals(role)) {
            insideOrder.setProduction(name);
            insideOrder.setProductionDate(DateUtil.getFormatedDate());
        }

        insideOrderDao.save(insideOrder);

        CheckRecord checkRecord = new CheckRecord();
        checkRecord.setCreateTime(DateUtil.getFormatedDateTime());
        checkRecord.setOperator(account);
        checkRecord.setOperatorName(name);
        checkRecord.setOrderNo(insideOrderCheckParam.getOrderNo());
        checkRecord.setReason(reason);
        checkRecord.setStatus(insideOrderCheckParam.getStatus());
        checkRecordDao.save(checkRecord);
        return MessageResult.success();
    }

    // 将当前订单的第一个默认的工艺做了
    @Transactional
    public void initFirstProduction(String orderNo) {
        // 先清空 再插入
        productionRecordDao.deleteAllByOrderNo(orderNo);
        List <OrderItem> orderItems = orderItemDao.findByOrderNo(orderNo);
        String time = DateUtil.getFormatedDateTime();
        for (OrderItem orderItem : orderItems) {
            String specs = orderItem.getSpecs();
            Production firstProduction = productionDao.findTopByOrderNoAndSpecs(orderNo, specs);
            List <String> temp = (List) JSONUtils.parse(firstProduction.getProcedures());
            if (temp.size() == 0) {
                continue;
            }
            String startNumber = orderItem.getNumberStart();
            List <ProductionRecord> list = new ArrayList <>();
            ProductionRecord productionRecord = new ProductionRecord();
            productionRecord.setRemark("系统生成");
            productionRecord.setStaffId(Constant.SYSTEM_STAFF_ID);
            productionRecord.setStaffNumber(Constant.SYSTEM_STAFF_NUMBER);
            productionRecord.setStaffName(Constant.SYSTEM_STAFF_NAME);
            productionRecord.setOrderNo(orderNo);
            productionRecord.setSpecs(specs);
            productionRecord.setSeque(orderItem.getSeque());
            productionRecord.setProductionId(firstProduction.getId());
            productionRecord.setProduction(temp.get(0));
            productionRecord.setCreateTime(time);
            productionRecord.setStatus("1");
            productionRecord.setStartTime(time);
            productionRecord.setNumber(startNumber);
            list.add(productionRecord);
            String nexNumber = startNumber;
            for (int i = 1; i < Integer.parseInt(orderItem.getAmount()); i++) {
                ProductionRecord productionRecord2 = new ProductionRecord();
                nexNumber = NumberUtil.nextNumber(nexNumber);
                BeanUtil.copyProperties(productionRecord, productionRecord2);
                productionRecord2.setNumber(nexNumber);
                list.add(productionRecord2);
            }
            productionRecordDao.saveAll(list);
        }

    }
}
